package com.cloudy.cloudspider.search;

import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by cloudy.xie on 18/1/16.
 */
public class LuceneWorkQueue {

    private Indexer indexer;
    private BlockingQueue<Set<SearchNewsModel>> queue = new LinkedBlockingQueue<>();
    private AtomicInteger currentNum = new AtomicInteger(0);
    private int totalNum;

    public LuceneWorkQueue(int totalNum){
        this.totalNum = totalNum;
        indexer = new Indexer("toutiao");
    }

    public void addTask(Set<SearchNewsModel> task){
        synchronized (queue){
            try {
                queue.put(task);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void run(){

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            try {
                Set<SearchNewsModel> task = queue.take();
                while(true){
                    System.out.println("start:"+currentNum.intValue()+",totalNum = "+totalNum);

                    if(task != null && !task.isEmpty()){
                        indexer.index(task);
                        currentNum.incrementAndGet();

                        System.out.println("end:"+currentNum.intValue() +",totalNum = "+totalNum);
                        if(totalNum<=currentNum.intValue()){
                            indexer.close();
                            executorService.shutdown();
                            break;
                        }
                    }
                    Thread.sleep(500);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
